<template>
  <BaseMainSlot
    v-loading="isShowData"
    element-loading-text="加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(255, 255, 255, 0.8)"
  >
    <template v-slot:btnsBar>
      <ActionBar
        v-if="!showDetail"
        :add-active="addActive"
        :del-active="delActive"
        :page-no="173"
        @add="add"
        @del="del"
      />
    </template>
    <template v-slot:searchbox>
      <div class="seach-box">
        <div class="select-box-content">
          <div class="select-box-content-name">标题：</div>
          <el-input
            v-model="title"
            clearable
            placeholder="请输入标题"
            @change="queryPageList()"
          />
        </div>
        <div class="select-box-content">
          <div class="select-box-content-name">设备类型：</div>
          <el-cascader
            v-model="equipmentTypeCode"
            :props="defaultProps"
            :options="equipmentTypeList"
            :show-all-levels="false"
            clearable
            @change="queryPageList()"
          />
        </div>
      </div>
    </template>
    <template v-slot:contentTitle v-if="!showDetail">
      <div class="info-box-title">知识列表</div>
    </template>

    <template v-slot:content>
      <div v-if="!showDetail" class="info-box-con">
        <div
          v-for="(item, index) in tableData"
          :key="index"
          class="info-box-con-one"
          :style="{ background: item.color }"
          @click="handleEdit(item)"
        >
          <div class="info-box-con-one-left">
            <el-checkbox
              v-model="item.checked"
              @change.native.stop="changeChecked(index)"
            />
            <svg-icon icon-class="library-icon" />
            <p>{{ item.title }}</p>
          </div>
          <div class="info-box-con-one-right">
            <p>{{ item.processMode }}</p>
            <div class="table-btns-box">
              <div class="table-btns edit-btns" @click="edit(item)">
                <i class="el-icon-edit-outline"></i>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-if="showDetail" class="article-box">
        <div class="table-btns-box flex-box">
          <div
            class="table-btns add-btns"
            @click="save()"
            v-if="judgePermission(173,'save')"
          >
            <i class="el-icon-s-tools"></i>
            <p>保存</p>
          </div>
          <div class="table-btns query-btns" @click="cancel()">
            <i class="el-icon-right"></i>
            <p>返回</p>
          </div>
        </div>
        <el-form
          ref="ruleForm"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item label="标题：" class="w50p" prop="title">
            <el-input v-model="formData.title" placeholder="请输入标题" clearable />
          </el-form-item>
          <el-form-item label="选择设备类型：" class="w50p" prop="equipmentTypeCode">
            <el-cascader
              v-model="formData.equipmentTypeCode"
              :props="defaultProps"
              :options="equipmentTypeList"
              :show-all-levels="false"
              clearable
              placeholder="请选择所属设备类型"
              @change="changeEquipmentTypeCode"
            />
          </el-form-item>
          <el-form-item label="设备型号：" class="w50p" prop="modelName">
            <el-select
              v-model="formData.modelName"
              clearable
              filterable
              placeholder="选择设备"
            >
              <el-option
                v-for="item of equipModelList"
                :key="item.equModelCode"
                :label="item.modelName"
                :value="item.equModelCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="备注：" class="w50p" prop="description">
            <el-input
              v-model="formData.description"
              clearable
              placeholder="请输入备注"
            />
          </el-form-item>
          <el-form-item label="处理方法：" class="w50p" prop="processMode">
            <el-input
              v-model="formData.processMode"
              clearable
              :rows="8"
              type="textarea"
              placeholder="请输入处理方法"
            />
          </el-form-item>
          <el-form-item label="视频：" class="w50p">
            <!-- <MultipleUpMany
            :can-input="false"
            @gave-files="gaveFiles"
            />-->
            <!-- <el-upload
              ref="upload"
              class="upload-file"
              action
              multiple
              :on-remove="(params) => handleRemove(params)"
              :https-request="(params) => handleFile(params)"
              :file-list="uploadFileList"
              accept=".png, .jpg, .jpeg, .pdf, .mp4"
            >
              <el-button type="text" class="add-many">
                <i class="el-icon-plus"></i>
              </el-button>
            </el-upload>-->
            <UploadPics
              ref="UploadPics"
              accept=".png, .jpg, .jpeg, .mp4"
              v-model="uploadFileList"
              @input="handlerAddFileList($event, 'video')"
              @delectFileId="handlerDeleteId($event, 'video')"
            ></UploadPics>
          </el-form-item>
        </el-form>
        <!-- <div class="data-info-box">
          <div v-if="pictureList.length > 0" class="article-content w100p">
            <p>图片:</p>
            <div class="data-info-box-img">
              <img
                v-for="(item, index) in pictureList"
                :key="index + 'pic'"
                :src="item.url"
                class="picture-con"
              />
            </div>
          </div>
          <div v-if="pdfList.length > 0" class="article-content w100p">
            <p>文件:</p>
            <div class="data-info-box-img">
              <img
                v-for="(item, index) in pdfList"
                :key="index"
                :src="item.url"
                class="picture-con"
                @click="click(item.url)"
              />
            </div>
          </div>
          <div v-if="videoList.length > 0" class="article-content w100p">
            <p>视频:</p>
            <div class="data-info-box-img">
              <video
                v-for="(item, index) in videoList"
                :key="index + 'video'"
                :src="item.url"
                @click="clickVideo(item.url)"
              ></video>
            </div>
          </div>
          <div
            v-if="
              pictureList.length === 0 &&
                pdfList.length === 0 &&
                videoList.length === 0 &&
                isShowData === false
            "
            class="empty-box"
          >暂无视频、图片等资料</div>
        </div> -->
      </div>
    </template>
  </BaseMainSlot>
</template>

<script>
import knowledgeBaseApi from "@/api/basic-info-manage/knowledge-base/index";
import BaseMainSlot from "@/components/BaseMainSlot/kong.vue";
import { mymixin } from "@/utils/mixin";
import equipTypeApi from "@/api/equip-manage/equip-type/index";
import ActionBar from "@/components/ActionBar";
import equipModelApi from "@/api/equip-manage/equip-model";
import { mapGetters } from "vuex";
import UploadPics from "@/components/UploadPics/upload-img-list.vue";

export default {
  name: "KnowledgeBase",

  components: { BaseMainSlot, ActionBar, UploadPics },
  mixins: [mymixin],
  data() {
    return {
      uploadPictureList: [],
      uploadVideoList: [],
      title: "",
      showDetail: false,
      defaultProps: {
        children: "childList",
        value: "equipmentTypeCode",
        label: "equipmentTypeName",
        emitPath: false,
        checkStrictly: true,
      },
      equipmentTypeCode: "",
      equipmentTypeList: [],
      formData: {},
      checkedIdList: [],
      uploadFileList: [],
      rules: {
        title: [
          {
            required: true,
            message: "请输入标题",
            trigger: ["change", "blur"],
          },
        ],
        equipmentTypeCode: [
          {
            required: true,
            message: "请选择设备类型",
            trigger: ["change", "blur"],
          },
        ],
        modelName: [
          {
            required: true,
            message: "请选择设备名称",
            trigger: ["change", "blur"],
          },
        ],
        processMode: [
          {
            required: true,
            message: "请输入处理方法",
            trigger: ["change", "blur"],
          },
        ],
        proposer: [
          {
            required: true,
            message: "请选择上报人",
            trigger: ["change", "blur"],
          },
        ],
      },
      // 查询设备型号
      equipModelList: [],
      pictureList: [],
      videoList: [],
      pdfList: [],
      isShowData: false,
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission",
    }),
  },
  watch: {
    showDetail(v) {
      console.log(v);
    },
  },
  created() {
    this.queryPageList();
    this.queryEquipmentType();
  },
  mounted() {},
  methods: {
    // 添加-轮播图/视频
    handlerAddFileList(data, type) {
      this.uploadFileList = data.list;
    },
    // 删除-轮播图/视频
    handlerDeleteId(file, type) {

      this.$confirm(
        `确认删除该${
          type === "png" ? "图片" : type === "video" ? "视频" : "文件"
        }`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          customClass: "myClass",
        }
      )
        .then(() => {
               // this.$confirm()
          if (!file.knowledgeImageId) {
            let fileId = file.url;
                  this.uploadFileList.splice(
                    this.uploadFileList.findIndex((i) => i.url == fileId),
                    1
                  );
                  return
          }
          // console.log(file)
          var form = new FormData();
          form.append("knowledgeImageId", file.knowledgeImageId);
          knowledgeBaseApi.delKnowledgeImage(form).then((res) => {
            if (res.code === 1) {
              let fileId = file.url;
              this.uploadFileList.splice(
                this.uploadFileList.findIndex((i) => i.url == fileId),
                1
              );
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 改变设备类型
    changeEquipmentTypeCode() {
      if (this.formData.equipmentTypeCode) {
        this.$set(this.formData, 'modelName', '')
        this.queryEquipModelList();
      }
    },
    // 查询设备型号
    queryEquipModelList() {
      // 获取数据
      let param = {
        page: 1,
        size: 10000,
        entity: {
          equipmentTypeCode: this.formData.equipmentTypeCode,
        },
      };
      if (!this.formData.equipmentTypeCode) {
        this.equipModelList = [];
        return;
      }
      equipModelApi.queryPageList(param).then((res) => {
        if (res.code === 1) {
          let data = res.data || {};
          this.equipModelList = data.content || [];
        }
      });
    },
    // 是否勾选
    changeChecked() {
      // this.tableData[index].checked = !this.tableData[index].checked
      this.tableData = [...this.tableData];
      this.checkedIdList = [];
      this.tableData.forEach((a) => {
        if (a.checked) {
          this.checkedIdList.push(a.repairKnowledgeCode);
        }
      });
      if (this.checkedIdList.length > 0) this.delActive = true;
      else this.resetActionBar();
    },
    // 关联设备类型
    queryEquipmentType() {
      this.loading = false;
      // 获取数据
      let param = {};
      equipTypeApi.queryTree(param).then((res) => {
        this.loading = false;
        if (res.code === 1) {
          let data = res.data || [];
          this.equipmentTypeList = data;
          this.queryEquipModelList();
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    queryPageList() {
      this.loading = false;
      // 获取数据
      let param = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          equipmentTypeCode: this.equipmentTypeCode,
          title: this.title,
        },
      };
      knowledgeBaseApi.queryPageList(param).then((res) => {
        this.loading = false;
        if (res.code === 1) {
          let data = res.data || {};
          this.totalSize = data.totalElements;
          this.tableData = data.content || [];
          this.tableData.forEach((a) => {
            this.$set(a, "checked", false);
          });
        }
      });
    },
    handleEdit(row) {
      if (row.repairKnowledgeId) {
        this.tableData.forEach((element) => {
          element.color = "rgba(0,0,0,0)";
        });
        this.$set(row, "color", "#02989A");
        this.tableData = [...this.tableData];
        this.formData = JSON.parse(JSON.stringify(row));
        this.addActive = true;
      } else {
        this.editObject = {};
        this.addActive = true;
      }
    },
    add() {
      this.formData = {};
      this.nowChanceStau = "add";
      this.titleText = "添加";
      this.addActive = false;
      this.delActive = false;
      this.showDetail = true;
    },
    edit(row) {
      if (row.repairKnowledgeId) {
        this.tableData.forEach((element) => {
          element.color = "rgba(0,0,0,0)";
        });
        this.$set(row, "color", "#02989A");
        this.tableData = [...this.tableData];
        this.formData = JSON.parse(JSON.stringify(row));
        this.nowChanceStau = "edit";
        this.titleText = "修改";
        this.addActive = false;
        this.delActive = false;
        this.showDetail = true;
        this.queryByRepairKnowledgeCode(this.formData.repairKnowledgeCode);
      } else {
        this.editObject = {};
        this.addActive = true;
      }
    },
    save() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          knowledgeBaseApi.add(this.formData).then((res) => {
            if (res.code === 1) {
              let data = res.data || {};
              this.$message.success(res.msg);
              if (this.uploadFileList.length > 0) {
                this.upPicture(data.repairKnowledgeCode);
              } else {
                this.close();
              }
            } else {
              this.$message.error(res.msg);
            }
          });
        }
      });
    },
    // 表格删除
    delmessage() {
      var form = new FormData();
      this.checkedIdList.forEach((a) => {
        form.append("repairKnowledgeCodeList", a);
      });
      knowledgeBaseApi.del(form).then((res) => {
        if (res.code === 1) {
          this.$message.success(res.msg);
          this.queryPageList();
        }
      });
    },
    cancel() {
      this.nowChanceStau = "";
      this.titleText = "";
      this.addActive = true;
      this.delActive = false;
      this.showDetail = false;
    },
    // 根据维修知识库编码查询影像数据
    queryByRepairKnowledgeCode(a) {
      // 获取数据
      var form = new FormData();
      form.append("repairKnowledgeCode", a);
      this.isShowData = true;
      knowledgeBaseApi.queryByRepairKnowledgeCode(form).then((res) => {
        this.isShowData = false;
        if (res.code === 1) {
          let data = res.data || [];
          this.pictureList = [];
          this.videoList = [];
          this.pdfList = [];
          if (data.length > 0) {
            data.forEach((a) => {
              a.name = a.pictureName;
              if (a.url.includes("common/file/upDown/videoView")) {
                // a.url = this.deal(a["imageData"]);
                this.videoList.push(a);
              } else if (a.url.includes("common/file/upDown/view")) {
                // a.url = "data:application/*;base64," + a.imageData;
                this.pictureList.push(a);
              } else if (a.pictureType === "application/pdf") {
                a.url =
                  "data:application/pdf;base64," + this.deal(a["imageData"]);
                this.pdfList.push(a);
              }
            });
          }
          this.uploadFileList = data;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    back() {
      this.showDetail = false;
    },
    deal(data) {
      // 获取到了blob对象
      let blob = this.base64ToBlob(data);
      // 获取当前url，直接放到iframe就能用，下载同理
      let blobURL = window.URL.createObjectURL(blob);
      return blobURL;
    },
    base64ToBlob(code) {
      // Base64一行不能超过76字符，超过则添加回车换行符。因此需要把base64字段中的换行符，回车符给去掉，有时候因为存在需要把加号空格之类的换回来，取决于base64存取时的规则。
      code = code.replace(/[\n\r]/g, "");
      var raw = window.atob(code);
      let rawLength = raw.length;
      // 转换成能直接解析的Uint8Array类型
      let uInt8Array = new Uint8Array(rawLength);
      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
      }
      return new Blob([uInt8Array], { type: "video/mp4" });
    },
    clickVideo(data) {
      window.open(data, "_blank");
    },
    handleRemove(file) {
      if (file.knowledgeImageId) {
        let index = this.uploadFileList.findIndex(
          (a) => a.knowledgeImageId === file.knowledgeImageId
        );
        if (index !== -1) {
          var form = new FormData();
          form.append("knowledgeImageId", file.knowledgeImageId);
          knowledgeBaseApi.delKnowledgeImage(form).then((res) => {
            if (res.code === 1) {
              this.uploadFileList.splice(index, 1);
            }
          });
        }
      } else {
        let index1 = this.uploadFileList.findIndex(
          (a) => a.uid === file.file.uid
        );
        if (index1 !== -1) {
          this.uploadFileList.splice(index1, 1);
        }
      }
    },
    // 上传文件
    handleFile(file) {
      this.loadFilesing = true;
      this.uploadFileList.push(file.file);
      this.loadFilesing = false;
    },
    upPicture(data) {
      var form = new FormData();
      this.uploadFileList.forEach((a) => {
        if (!a.repairKnowledgeId) {
          form.append("urlList", a.url);
        }
      });
      form.append("repairKnowledgeCode", data);
      knowledgeBaseApi.addKnowledgeImageNew(form).then((res) => {
        if (res.code === 1) {
          // this.$message.success(res.msg);
          this.close();
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // clickVideo(data) {
    //   window.open(data, "_blank");
    // },
    close() {
      this.showDetail = false;
      this.uploadFileList = [];
      this.pdfList = [];
      this.videoList = [];
      this.pictureList = [];
      this.queryPageList();

    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/styles/variables.scss";

.info-box-title {
  position: relative;
  padding: 6px 0 6px 48px;
  color: #00fff7;
  font-size: 18px;
  height: 57px;
  letter-spacing: 2px;
  display: flex;
  align-items: center;
  background-color: $hamburgerBgColor;
  &:before {
    content: "";
    position: absolute;
    width: 7px;
    height: 30px;
    left: 31px;
    top: 14px;
    background-color: #00fff7;
  }
}
.info-box-con {
  height: calc(100% - 80px);
  max-height: 700px;
  padding: 0 20px;
  border-bottom: 30px solid $contentColor;
  font-weight: 400;
  letter-spacing: 2px;
  overflow-y: auto;
  .info-box-con-one {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: inset 0px 0px 8px 1px #00fff7;
    border-radius: 5px 5px 5px 5px;
    opacity: 1;
    border: 1px solid #00fff7;
    padding: 0 20px;
    font-size: 18px;
    margin: 16px 0;
    .info-box-con-one-left {
      display: flex;
      align-items: center;
      > p {
        margin: 0 10px;
        white-space: nowrap;
      }
    }
    .info-box-con-one-right {
      display: flex;
      align-items: center;
      > p {
        margin-right: 20px;
      }
    }
  }
}
.cancelback {
  position: absolute;
  height: 34px;
  width: auto;
  top: -20px;
  right: 0;
  cursor: pointer;
  right: 20px;
  &:hover {
    transform: scale(1.1);
  }
}

.article-box {
  padding: 5% 5%;
  width: 100%;
  // height: 100%;
  background-color: $hamburgerBgColor;
}
.el-input__inner {
  color: #000;
  border-color: rgba(217, 217, 217, 1);
  background-color: rgba(255, 255, 255, 1);
}
.el-textarea__inner {
  color: #000;
  border-color: rgba(217, 217, 217, 1);
  background-color: rgba(255, 255, 255, 1);
}
.el-form {
  margin-top: 30px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-between;
  .total-price {
    color: #000;
  }
  .el-row {
    width: 100%;
    margin-bottom: 10px;
    .el-table {
      max-height: 200px;
      overflow-y: auto;
      background-color: rgba(255, 255, 255, 1);
      .cell {
        color: #000;
      }
      th {
        background-color: rgba(230, 230, 230, 1);
      }
      th.is-leaf {
        border-color: rgba(77, 77, 77, 1);
      }
      td {
        border-color: rgba(77, 77, 77, 1);
      }
      tr:hover {
        background-color: rgba(77, 77, 77, 1);
      }
      .el-table__empty-text {
        color: #000;
      }
      .current-row {
        // background-color: rgb(177, 177, 177);
        background-color: #dbdbdb !important;
      }
      .el-table__row--striped {
        background-color: rgba(255, 255, 255, 1);
      }
      // color: #000;
    }
    .el-table--border {
      border-color: rgba(77, 77, 77, 1);
      border-top-left-radius: 8px;
      border-top-right-radius: 8px;
    }
    .el-table--enable-row-hover .el-table__body tr:hover > td {
      background-color: rgb(177, 177, 177);
    }
    .el-table__body tr.current-row > td {
      background-color: #dbdbdb !important;
    }
    // .el-button {
    //   width: 100%;
    // }
    .el-form {
      // width: 100%;
      // margin: ;
      .el-form-item {
        margin-bottom: 0 !important;
      }
      .el-form-item__content {
        display: flex;
        width: 100%;
        .el-select {
          min-width: 15%;
        }
        .el-input {
          min-width: 10%;
        }
        .el-input__inner {
          border-right: none;
        }
        .el-button {
          min-width: 5%;
          margin-left: 10px;
        }
      }
    }
  }
}
::v-deep .el-form-item {
  display: flex;
  .el-form-item__label {
    line-height: 36px;
    min-width: 140px;
    text-align: end;
  }
  .el-form-item__content {
    line-height: 36px;
    width: 100%;
    display: flex;
  }
}
::v-deep .el-checkbox:last-of-type {
  margin-right: 10px;
}
.add-many {
  border: 1px solid #6ecae3;
  width: 40px;
  height: 40px;
  padding: 0;
  background-color: transparent;
  line-height: 40px;
  border-radius: 4px;
  color: rgb(161, 154, 154);
  font-weight: 600;
  i {
    font-size: 40px;
  }
}
::v-deep .el-upload-list__item-name {
  color: #fff;
}
.flex-box {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.data-info-box {
  width: 100%;
}
.article-content {
  font-size: 15px;
  font-weight: 400;
  color: #ffffff;
  line-height: 33px;
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
  > p {
    margin: 0;
    white-space: nowrap;
    min-width: 140px;
    padding: 0 24px 0 0;
    font-size: 700;
    text-align: right;
  }
  .data-info-box-img {
    max-width: calc(100% - 100px);
    display: flex;
    flex-direction: column;
    > video {
      width: 100%;
    }
    > img {
      width: 100%;
    }
  }
}
.empty-box {
  font-size: 22px;
  color: red;
  width: 100%;
  text-align: center;
}
</style>
